{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "google",
   "metadata": {},
   "source": [
    "##### Copyright 2025 Google LLC."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "apache",
   "metadata": {},
   "source": [
    "Licensed under the Apache License, Version 2.0 (the \"License\");\n",
    "you may not use this file except in compliance with the License.\n",
    "You may obtain a copy of the License at\n",
    "\n",
    "    http://www.apache.org/licenses/LICENSE-2.0\n",
    "\n",
    "Unless required by applicable law or agreed to in writing, software\n",
    "distributed under the License is distributed on an \"AS IS\" BASIS,\n",
    "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
    "See the License for the specific language governing permissions and\n",
    "limitations under the License.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "basename",
   "metadata": {},
   "source": [
    "# discrete_tomography"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "link",
   "metadata": {},
   "source": [
    "<table align=\"left\">\n",
    "<td>\n",
    "<a href=\"https://colab.research.google.com/github/google/or-tools/blob/main/examples/notebook/contrib/discrete_tomography.ipynb\"><img src=\"https://raw.githubusercontent.com/google/or-tools/main/tools/colab_32px.png\"/>Run in Google Colab</a>\n",
    "</td>\n",
    "<td>\n",
    "<a href=\"https://github.com/google/or-tools/blob/main/examples/contrib/discrete_tomography.py\"><img src=\"https://raw.githubusercontent.com/google/or-tools/main/tools/github_32px.png\"/>View source on GitHub</a>\n",
    "</td>\n",
    "</table>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "doc",
   "metadata": {},
   "source": [
    "First, you must install [ortools](https://pypi.org/project/ortools/) package in this colab."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "install",
   "metadata": {},
   "outputs": [],
   "source": [
    "%pip install ortools"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "description",
   "metadata": {},
   "source": [
    "\n",
    "\n",
    "  Discrete tomography in Google CP Solver.\n",
    "\n",
    "  Problem from http://eclipse.crosscoreop.com/examples/tomo.ecl.txt\n",
    "  '''\n",
    "  This is a little 'tomography' problem, taken from an old issue\n",
    "  of Scientific American.\n",
    "\n",
    "  A matrix which contains zeroes and ones gets \"x-rayed\" vertically and\n",
    "  horizontally, giving the total number of ones in each row and column.\n",
    "  The problem is to reconstruct the contents of the matrix from this\n",
    "  information. Sample run:\n",
    "\n",
    "  ?- go.\n",
    "    0 0 7 1 6 3 4 5 2 7 0 0\n",
    " 0\n",
    " 0\n",
    " 8      * * * * * * * *\n",
    " 2      *             *\n",
    " 6      *   * * * *   *\n",
    " 4      *   *     *   *\n",
    " 5      *   *   * *   *\n",
    " 3      *   *         *\n",
    " 7      *   * * * * * *\n",
    " 0\n",
    " 0\n",
    "\n",
    " Eclipse solution by Joachim Schimpf, IC-Parc\n",
    " '''\n",
    "\n",
    " Compare with the following models:\n",
    " * Comet: http://www.hakank.org/comet/discrete_tomography.co\n",
    " * Gecode: http://www.hakank.org/gecode/discrete_tomography.cpp\n",
    " * MiniZinc: http://www.hakank.org/minizinc/tomography.mzn\n",
    " * Tailor/Essence': http://www.hakank.org/tailor/tomography.eprime\n",
    " * SICStus: http://hakank.org/sicstus/discrete_tomography.pl\n",
    "\n",
    "  This model was created by Hakan Kjellerstrand (hakank@gmail.com)\n",
    "  Also see my other Google CP Solver models:\n",
    "  http://www.hakank.org/google_or_tools/\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "code",
   "metadata": {},
   "outputs": [],
   "source": [
    "import sys\n",
    "from ortools.constraint_solver import pywrapcp\n",
    "\n",
    "\n",
    "def main(row_sums=\"\", col_sums=\"\"):\n",
    "\n",
    "  # Create the solver.\n",
    "  solver = pywrapcp.Solver(\"n-queens\")\n",
    "\n",
    "  #\n",
    "  # data\n",
    "  #\n",
    "  if row_sums == \"\":\n",
    "    print(\"Using default problem instance\")\n",
    "    row_sums = [0, 0, 8, 2, 6, 4, 5, 3, 7, 0, 0]\n",
    "    col_sums = [0, 0, 7, 1, 6, 3, 4, 5, 2, 7, 0, 0]\n",
    "\n",
    "  r = len(row_sums)\n",
    "  c = len(col_sums)\n",
    "\n",
    "  # declare variables\n",
    "  x = []\n",
    "  for i in range(r):\n",
    "    t = []\n",
    "    for j in range(c):\n",
    "      t.append(solver.IntVar(0, 1, \"x[%i,%i]\" % (i, j)))\n",
    "    x.append(t)\n",
    "  x_flat = [x[i][j] for i in range(r) for j in range(c)]\n",
    "\n",
    "  #\n",
    "  # constraints\n",
    "  #\n",
    "  [\n",
    "      solver.Add(solver.Sum([x[i][j]\n",
    "                             for j in range(c)]) == row_sums[i])\n",
    "      for i in range(r)\n",
    "  ]\n",
    "  [\n",
    "      solver.Add(solver.Sum([x[i][j]\n",
    "                             for i in range(r)]) == col_sums[j])\n",
    "      for j in range(c)\n",
    "  ]\n",
    "\n",
    "  #\n",
    "  # solution and search\n",
    "  #\n",
    "  solution = solver.Assignment()\n",
    "  solution.Add(x_flat)\n",
    "\n",
    "  # db: DecisionBuilder\n",
    "  db = solver.Phase(x_flat, solver.INT_VAR_SIMPLE, solver.ASSIGN_MIN_VALUE)\n",
    "\n",
    "  solver.NewSearch(db)\n",
    "  num_solutions = 0\n",
    "  while solver.NextSolution():\n",
    "    print_solution(x, r, c, row_sums, col_sums)\n",
    "    print()\n",
    "\n",
    "    num_solutions += 1\n",
    "  solver.EndSearch()\n",
    "\n",
    "  print()\n",
    "  print(\"num_solutions:\", num_solutions)\n",
    "  print(\"failures:\", solver.Failures())\n",
    "  print(\"branches:\", solver.Branches())\n",
    "  print(\"WallTime:\", solver.WallTime())\n",
    "\n",
    "\n",
    "#\n",
    "# Print solution\n",
    "#\n",
    "\n",
    "\n",
    "def print_solution(x, rows, cols, row_sums, col_sums):\n",
    "  print(\"  \", end=\" \")\n",
    "  for j in range(cols):\n",
    "    print(col_sums[j], end=\" \")\n",
    "  print()\n",
    "  for i in range(rows):\n",
    "    print(row_sums[i], end=\" \")\n",
    "    for j in range(cols):\n",
    "      if x[i][j].Value() == 1:\n",
    "        print(\"#\", end=\" \")\n",
    "      else:\n",
    "        print(\".\", end=\" \")\n",
    "    print(\"\")\n",
    "\n",
    "\n",
    "#\n",
    "# Read a problem instance from a file\n",
    "#\n",
    "def read_problem(file):\n",
    "  f = open(file, \"r\")\n",
    "  row_sums = f.readline()\n",
    "  col_sums = f.readline()\n",
    "  row_sums = [int(r) for r in (row_sums.rstrip()).split(\",\")]\n",
    "  col_sums = [int(c) for c in (col_sums.rstrip()).split(\",\")]\n",
    "\n",
    "  return [row_sums, col_sums]\n",
    "\n",
    "\n",
    "if len(sys.argv) > 1:\n",
    "  file = sys.argv[1]\n",
    "  print(\"Problem instance from\", file)\n",
    "  [row_sums, col_sums] = read_problem(file)\n",
    "  main(row_sums, col_sums)\n",
    "else:\n",
    "  main()\n",
    "\n"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
